package com.IC.base.controller;

import com.IC.base.service.ActualEquipmentService;
import IC.common.core.domain.R;
import com.IC.domain.po.AccessControlRecordPO;
import com.github.pagehelper.PageInfo;
import com.IC.domain.dto.ActualEquipmentDTO;
import com.IC.domain.po.ActualEquipmentPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static org.apache.ibatis.ognl.DynamicSubscript.all;

@RestController
@RequestMapping("/equipment")
public class ActualEquipmentController {

    @Autowired
    private ActualEquipmentService actualEquipmentService;
    @Autowired
    private RedisTemplate<String, Object> baseRedisTemplate;

    /**
     * 查询实有设备信息
     * @param actualEquipmentDTO
     * @return
     */
    @PostMapping("/list")
    public R list(@RequestBody ActualEquipmentDTO actualEquipmentDTO){
        PageInfo<ActualEquipmentPO> list = actualEquipmentService.findList(actualEquipmentDTO);
        return R.ok(list);
    }

    /**
     * 添加设备
     * @param actualEquipmentPO
     * @return
     */
    @PostMapping("/add")
    public R add(@RequestBody ActualEquipmentPO actualEquipmentPO){
        actualEquipmentService.save(actualEquipmentPO);
        refreshCache();
        return R.ok();
    }

    /**
     * 修改设备
     * @param actualEquipmentPO
     * @return
     */
    @PostMapping("/update")
    public R update(@RequestBody ActualEquipmentPO actualEquipmentPO){
        actualEquipmentService.updateById(actualEquipmentPO);
        refreshCache();
        return R.ok();
    }

    /**
     * 删除设备
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    public R delete(@PathVariable Long id){
        actualEquipmentService.removeById(id);
        refreshCache();
        return R.ok();
    }

    /**
     * 查询设备下拉框
     * @param actualEquipmentPO
     * @return
     */
    @GetMapping("/all")
    public R all(){
        List<ActualEquipmentPO> all = (List<ActualEquipmentPO>) baseRedisTemplate.opsForValue().get("ActualEquipment");
        if(all==null){
            all = actualEquipmentService.all();
            baseRedisTemplate.opsForValue().set("ActualEquipment",all);
        }
        return R.ok(all);
    }

    @GetMapping("getInfo")
    public void getInfo(){
        System.out.println("ahahha");
    }

    @GetMapping("forInfo")
    public void forInfo(){
        System.out.println("哈哈哈");
        for (int i = 0; i < 10; i++) {
            this.getInfo();
        }
    }

    private void cacheAllData() {
        List<ActualEquipmentPO> list = actualEquipmentService.list();
        baseRedisTemplate.opsForValue().set("ActualEquipment", list);
    }

    @Scheduled(fixedRate = 10000) // 每10秒执行一次
    public void refreshCache() {
        cacheAllData();
    }

}
